<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/20/020
 * Time: 16:04
 */

namespace App\Controller;


use App\Model\FriendsModel;
use App\Model\UserModel;
use lib\View;

class FriendController
{
    public function addFriends(){
        $fids=[];
        $user=new UserModel('user','uid');
        $friend=new FriendsModel('friends','id');
        $uid=isset($_SESSION['uid'])?$_SESSION['uid']:'';
        $username=isset($_SESSION['username'])?$_SESSION['username']:'';
        $friends=$user->get();
      // print_r($friends);exit();
        $friendid=$friend->get(['uid'=>$uid]);
        foreach ($friendid as $id){
         $fids[]=$id['fid'];
        }
        foreach ($friends as $k=>$f){
            if($f['uid']==$uid){
                unset($friends[$k]);
            }
            if (in_array($f['uid'],$fids)){
               unset($friends[$k]);
            }
        }
        $friendlist=$user->join(['friends'=>'fid'],['friends.uid'=>$uid]);
        return new View('addfriends',['friends'=>$friends,'uid'=>$uid,'username'=>$username,'friendlist'=>$friendlist]);
    }
    public function add_friend(){
        $uid=$this->input('uid');
        $fid=$this->input('fid');
        $friend=new FriendsModel('friends','id');
        $row=$friend->get(['uid'=>$uid,'fid'=>$fid]);
        //print_r($row);exit();
        if (count($row)>0){
            echo "<script>alert('您已经添加过ta为好友');history.back();</script>";

           return;
        }
         $friend->save(['uid'=>$uid,'fid'=>$fid]);
         echo "<script>alert('添加好友成功');history.back();</script>";

    }
    public function delete_friend(){
        $fid=$this->input('fid');
        $uid=$this->input('uid');
        //echo $fid;exit();
        $friend=new FriendsModel('friends','id');
       if ($friend->delete(['fid'=>$fid,'uid'=>$uid])){
           echo "<script>alert('删除好友成功');history.back();</script>";
       }
    }
    public function input($name)
    {
        return htmlspecialchars(stripslashes($_REQUEST[$name]));
    }
}